package com.zipking.cloud.springbootmybatis.current;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
    private final CyclicBarrier barrier;

    public CyclicBarrierTest(int numberOfRunners) {
        barrier = new CyclicBarrier(numberOfRunners, () -> {
            System.out.println("比赛开始！");
            // 这里可以放置所有参与者到达屏障后要执行的操作
        });
    }

    public void run() {
        System.out.println("等待其他参赛者...");
        try {
            barrier.await(); // 等待其他线程
            System.out.println("开始跑步！");
            // 跑步时间
            Thread.sleep((long) (Math.random() * 10000));
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        final int numberOfRunners = 5;
        CyclicBarrierTest race = new CyclicBarrierTest(numberOfRunners);

        // 创建参赛者线程
        for (int i = 0; i < numberOfRunners; i++) {
            final int runnerNumber = i + 1;
            new Thread(() -> {
                System.out.println("参赛者 " + runnerNumber + " 已准备就绪");
                race.run();
            }).start();
        }
    }
}

